package com.example.demo.web.util;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttCallback;
import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttConnectOptions;
import org.eclipse.paho.client.mqttv3.MqttMessage;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.fasterxml.jackson.databind.ObjectMapper;

public class PushCallback implements MqttCallback {
	 private static ObjectMapper mapper; 
     private static com.fasterxml.jackson.databind.JsonNode rootNode;
	 private Logger logger = LogManager.getLogger(PushCallback.class);
	
	 private MqttClient client;
	 private MqttConnectOptions options;
	 private String topic;
	 private int qos;
	 
	 public PushCallback(MqttClient client, MqttConnectOptions options,String topic,int qos) {
         this.client = client;
         this.options = options;
         this.topic=topic;
         this.qos=qos;
     }
	 
	/**
	 * 断开重连
	 */
	 public void connectionLost(Throwable cause) {  
		 logger.info("MQTT连接断开，发起重连");
		 while(true) {
			 try {
			   Thread.sleep(10000);
			   client.connect(options);
	            //订阅消息  
	            client.subscribe(topic,qos); 
	            logger.info("MQTT重新连接成功:"+client);
			     break;
			   } catch (Exception e) {
			         e.printStackTrace();
			           continue;
			  }
	     }
		  
	 }   
  
	public void messageArrived(String topic, MqttMessage message) throws Exception {
        System.out.println("MQTT Rece:" + message.toString());
        try {
        	mapper = new ObjectMapper(); 
			rootNode = mapper.readTree(message.toString());
			String type =rootNode.get("type").asText();
			System.out.println("Parsed type:" + type);
			if(type.equalsIgnoreCase("hbeat")) {
				rabbitSender.rabbitsender.msend("TlockExchange","tp.hbeat", rootNode);
			}else {
				rabbitSender.rabbitsender.msend("TlockExchange","tp.cloud", rootNode);
			}
        	
        }catch(Exception e) {
        	
        	e.printStackTrace();
        }
	
    }

    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
